package com.wrupple.muba.catalogs.client.module.services.logic.impl;

import java.util.List;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayMixed;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.wrupple.muba.catalogs.client.module.services.logic.CatalogEntryAssembler;
import com.wrupple.muba.catalogs.domain.CatalogEntry;
import com.wrupple.vegetate.client.util.JsArrayList;
import com.wrupple.vegetate.domain.JsVegetateResultSet;

public class CatalogEntryAssemblerImpl implements CatalogEntryAssembler {

	@Override
	public JsArray<CatalogEntry> processResultSet(
			JsVegetateResultSet resultSet, String catalogid) {
		List<CatalogEntry> list = null;
		JsArray<CatalogEntry> arrayList;
		JsArrayString fields = resultSet.getColumnNames();
		CatalogEntry emptyEntry = null;
		JsArrayMixed fieldContents;
		JSONArray fieldContentsWrapper;
		JSONObject catalogEntryWrapper;
		JSONValue fieldValue;
		
		String fieldId;
		for (int i = 0; i < fields.length(); i++) {
			//field's name
			fieldId = fields.get(i);
			//summarized field contents
			fieldContents = resultSet.getColumn(fieldId);
			
			if (fieldContents != null) {
				int size = fieldContents.length();
				if (list == null) {
					//first time, create assembled entries list
					arrayList = JavaScriptObject.createArray().cast();
					list = JsArrayList.arrayAsList(arrayList);

					//create empty entries, fill values as fields pass by
					for (int j = 0; j < size; j++) {
						emptyEntry = CatalogEntry.createCatalogEntry(catalogid);
						list.add(emptyEntry);
					}
				}

				fieldContentsWrapper = new JSONArray(fieldContents);

				for (int j = 0; j < size; j++) {
					catalogEntryWrapper = new JSONObject(list.get(j));
					fieldValue = fieldContentsWrapper.get(j);
					catalogEntryWrapper.put(fieldId, fieldValue);
					emptyEntry = catalogEntryWrapper.getJavaScriptObject()
							.cast();
					list.set(j, emptyEntry);
				}

			}
		}
		return JsArrayList.unwrap(list);
	}
	
	protected final native void setCatalog(JavaScriptObject entry, String id) /*-{
	entry["catalog"] = id;
	}-*/;
}
